use std::fs::{File, OpenOptions};
use std::io::{self, Write};
use std::path::Path;
use crate::error::ServerError;
use crate::protocol::task::TaskStatus;
use crate::tasks::task::Task;
use once_cell::sync::OnceCell;
use std::sync::Mutex;
use lazy_static::lazy_static;

const LOG_FILE_PATH: &str = "edp_files/logs/task_history.csv";

pub struct TaskSummaryLogger {
    file_path: String,
}

impl TaskSummaryLogger {
    pub fn new() -> Self {
        TaskSummaryLogger {
            file_path: LOG_FILE_PATH.to_string(),
        }
    }

    pub fn log_task(&self, task: &Task) -> io::Result<()> {
        let file_exists = Path::new(&self.file_path).exists();
        
        if let Some(path) = Path::new(&self.file_path).parent() {
            if !path.exists() {
                std::fs::create_dir_all(path)?;
            }
        }
        let mut file = OpenOptions::new()
            .append(true)
            .create(true)
            .open(&self.file_path)?;
        
        if !file_exists {
            writeln!(file, "服务名称,服务地址,任务名称,创建时间,完成时间,任务退出状态")?;
        }
        
        write!(file, "{},{},{},{},", task.service_name, task.service_addr, task.name, task.created_at)?;
        match task.completed_at {
            Some(completed_at) => {
                write!(file, "{},{:?}", completed_at, task.status)?;
            }
            None => {
                write!(file, "-,{:?}", task.status)?;
            }
        }
        writeln!(file)?;
        Ok(())
    }
    
    pub fn clear_log(&self) -> io::Result<()> {
        File::create(&self.file_path)?;
        Ok(())
    }

    fn escape_string(&self, s: &String) -> String {
        format!("\"{}\"", s.replace("\"", "\"\""))
    }
}

lazy_static! {
    pub static ref TASK_SUMMARY_LOGGER: Mutex<TaskSummaryLogger> = Mutex::new(TaskSummaryLogger::new());
}


